'use strict';
const crypto = require('crypto');

// 生成卡密
const generateCode = (length = 16) => {
  // 确保长度在合理范围内
  if (length < 8 || length > 32) {
    throw new Error('卡密长度必须在8-32位之间');
  }
  
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let code = '';
  for (let i = 0; i < length; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return code;
};

// 验证卡密格式
const validateCode = (code) => {
  // 检查长度是否在合理范围内
  if (code.length < 8 || code.length > 32) {
    return {
      valid: false,
      message: '卡密长度必须在8-32位之间'
    };
  }
  
  // 检查是否只包含大写字母和数字
  if (!/^[A-Z0-9]+$/.test(code)) {
    return {
      valid: false,
      message: '卡密只能包含大写字母和数字'
    };
  }
  
  return {
    valid: true
  };
};

// 检查卡密是否已存在
const isCodeExists = async (db, code) => {
  try {
    const { data } = await db.collection('activation_codes')
      .where({ code: code })
      .get();
    return data && data.length > 0;
  } catch (error) {
    console.error('检查卡密是否存在失败:', error);
    throw error;
  }
};

// 生成唯一卡密
const generateUniqueCode = async (db) => {
  let code;
  let exists = true;
  let attempts = 0;
  const maxAttempts = 5;

  while (exists && attempts < maxAttempts) {
    code = generateCode();
    exists = await isCodeExists(db, code);
    attempts++;
  }

  if (attempts >= maxAttempts) {
    throw new Error('无法生成唯一卡密，请重试');
  }

  return code;
};

// 验证管理员权限
const verifyAdmin = async (token) => {
  try {
    const db = uniCloud.database();
    const { data } = await db.collection('admin').where({
      token: token
    }).get();
    return data && data.length > 0;
  } catch (error) {
    console.error('验证管理员权限失败:', error);
    return false;
  }
};

// 批量验证卡密唯一性
const validateBatchCodes = async (db, codes) => {
  try {
    const { data } = await db.collection('activation_codes')
      .where({
        code: db.command.in(codes)
      })
      .get();
    
    const existingCodes = new Set(data.map(item => item.code));
    const duplicates = codes.filter(code => existingCodes.has(code));
    
    return {
      valid: duplicates.length === 0,
      duplicates: duplicates
    };
  } catch (error) {
    console.error('验证批量卡密失败:', error);
    throw error;
  }
};

exports.main = async (event, context) => {
  console.log('云函数被调用，参数:', JSON.stringify(event, null, 2));
  
  const { action, code, count, codes, page = 1, pageSize = 20, token } = event;
  
  // 验证管理员权限
  try {
    const db = uniCloud.database();
    const adminCollection = db.collection('admin');
    console.log('开始验证管理员权限...');
    
    // 查询管理员记录
    const adminQuery = await adminCollection.where({
      token: token
    }).get();
    
    console.log('管理员查询结果:', {
      hasData: !!adminQuery.data,
      dataLength: adminQuery.data ? adminQuery.data.length : 0
    });
    
    if (!adminQuery.data || adminQuery.data.length === 0) {
      console.log('管理员验证失败：未找到匹配的管理员记录');
      return {
        success: false,
        message: '未登录或登录已过期'
      };
    }
    
    console.log('管理员验证成功');
  } catch (error) {
    console.error('验证管理员权限失败，详细错误:', {
      message: error.message,
      stack: error.stack
    });
    return {
      success: false,
      message: '验证权限失败：' + error.message
    };
  }

  try {
    const db = uniCloud.database();
    const codeCollection = db.collection('activation_codes');
    
    switch (action) {
      case 'list': {
        try {
          console.log('开始获取卡密列表，分页参数:', { page, pageSize, searchKeyword: event.searchKeyword });
          
          const _ = db.command;
          
          // 构建查询条件
          let whereCondition = {};
          if (event.searchKeyword) {
            // 使用正则表达式进行模糊匹配
            whereCondition.code = new RegExp(event.searchKeyword, 'i');
          }
          
          // 计算总数
          const countResult = await codeCollection.where(whereCondition).count();
          if (!countResult || typeof countResult.total !== 'number') {
            throw new Error('获取总数失败');
          }
          const total = countResult.total;
          console.log('数据库总数:', total);
          
          // 分页查询
          const skip = (page - 1) * pageSize;
          console.log('查询参数:', { skip, limit: pageSize, whereCondition });
          
          const queryResult = await codeCollection
            .where(whereCondition)
            .orderBy('createTime', 'desc')
            .skip(skip)
            .limit(pageSize)
            .get();
            
          if (!queryResult || !Array.isArray(queryResult.data)) {
            throw new Error('查询结果格式错误');
          }
          
          const { data } = queryResult;
          
          console.log('查询结果:', {
            total,
            page,
            pageSize,
            dataLength: data.length,
            firstRecord: data[0] ? {
              code: data[0].code,
              status: data[0].status,
              createTime: data[0].createTime
            } : '无数据'
          });
          
          return {
            success: true,
            codes: data,
            total,
            page,
            pageSize,
            hasMore: skip + data.length < total
          };
        } catch (error) {
          console.error('获取卡密列表失败，详细错误:', {
            message: error.message,
            stack: error.stack
          });
          throw new Error('获取卡密列表失败：' + error.message);
        }
      }
      
      case 'generate': {
        if (!count || count < 1) {
          return {
            success: false,
            message: '生成数量必须大于0'
          };
        }
        
        if (count > 100) {
          return {
            success: false,
            message: '单次生成数量不能超过100个'
          };
        }
        
        // 获取自定义长度，如果没有指定则使用默认值16
        const codeLength = event.codeLength || 16;
        
        try {
          const codes = [];
          for (let i = 0; i < count; i++) {
            const code = generateCode(codeLength);
            codes.push({
              code,
              status: 'unused',
              createTime: Date.now(),
              createBy: token,
              deviceId: null,
              lastLoginTime: null,
              lastLoginIP: null,
              lastLoginUA: null
            });
          }
          
          await codeCollection.add(codes);
          
          return {
            success: true,
            message: `成功生成 ${count} 个卡密`,
            codes: codes.map(item => item.code)
          };
        } catch (error) {
          return {
            success: false,
            message: error.message || '生成卡密失败'
          };
        }
      }
      
      case 'batchImport': {
        if (!codes || !Array.isArray(codes) || codes.length === 0) {
          return {
            success: false,
            message: '卡密列表不能为空'
          };
        }
        
        if (codes.length > 100) {
          return {
            success: false,
            message: '单次导入数量不能超过100个'
          };
        }
        
        // 验证所有卡密格式
        const invalidCodes = [];
        for (const code of codes) {
          const validation = validateCode(code);
          if (!validation.valid) {
            invalidCodes.push({
              code,
              reason: validation.message
            });
          }
        }
        
        if (invalidCodes.length > 0) {
          return {
            success: false,
            message: '存在格式不正确的卡密',
            invalidCodes: invalidCodes
          };
        }
        
        // 检查重复卡密
        const existingCodes = await codeCollection.where({
          code: db.command.in(codes)
        }).get();
        
        if (existingCodes.data.length > 0) {
          return {
            success: false,
            message: '存在重复卡密',
            duplicates: existingCodes.data.map(item => item.code)
          };
        }
        
        const codeList = codes.map(code => ({
          code,
          status: 'unused',
          createTime: Date.now(),
          createBy: token,
          deviceId: null,
          lastLoginTime: null,
          lastLoginIP: null,
          lastLoginUA: null
        }));
        
        await codeCollection.add(codeList);
        
        return {
          success: true,
          message: `成功导入 ${codes.length} 个卡密`,
          total: codes.length
        };
      }
      
      case 'disable':
      case 'enable': {
        if (!code) {
          return {
            success: false,
            message: '卡密不能为空'
          };
        }
        
        const status = action === 'disable' ? 'disabled' : 'unused';
        await codeCollection.where({ code }).update({
          status,
          updateTime: Date.now()
        });
        
        return {
          success: true,
          message: action === 'disable' ? '卡密已禁用' : '卡密已启用'
        };
      }
      
      case 'delete': {
        if (!code) {
          return {
            success: false,
            message: '卡密不能为空'
          };
        }
        
        await codeCollection.where({ code }).remove();
        
        return {
          success: true,
          message: '卡密已删除'
        };
      }
      
      default:
        return {
          success: false,
          message: '未知操作'
        };
    }
  } catch (error) {
    console.error('操作失败，详细错误:', {
      message: error.message,
      stack: error.stack
    });
    return {
      success: false,
      message: '操作失败：' + (error.message || '未知错误')
    };
  }
}; 